package com.yingside.thread.ball;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class BallFrame2 extends JFrame {

    private JButton btnMove;
    private JPanel panel;
    private int x = 30,y = 30;

    public BallFrame2(){
        this.setTitle("移动的小球");
        this.setBounds(200,100,400,400);

        BallPanel bp = new BallPanel();


        panel = new JPanel();
        btnMove = new JButton("移动");

        btnMove.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Thread t = new Thread(bp);
                t.start();
            }
        });
        panel.add(btnMove);
        this.add(bp, BorderLayout.CENTER);
        this.add(panel, BorderLayout.SOUTH);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

    }

    public class BallPanel extends JPanel implements Runnable{

        @Override
        public void paint(Graphics g) {
            super.paint(g);

            g.fillOval(x,y,50,50);
        }

        @Override
        public void run() {
            try{
                for (int i = 1; i < 50; i++) {
                    x += 3;
                    Thread.sleep(100);
                    repaint();
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {

        BallFrame2 bf = new BallFrame2();
    }

}
